// index.js
// 获取应用实例
import { mallApi } from '/api/mall'
import { getNotifications } from '/store/actions'
import { isLogin } from '/store/mutations'
import { GlobalData } from '/store/state'
import { $event, $utils } from '/utils'

Page({
  data: {
    navigationHeight: GlobalData.navigationHeight,
    access: GlobalData.access,
    currencyName: GlobalData.currencyName,
    noMore: false,
    navData: [
      {
        id: 0,
        name: '推荐',
        icon: { url: GlobalData.mall.all_categories_icon.url },
        page: 1,
        isLastPage: false,
      },
    ] as any[],
    currentTab: 0,
    navScrollLeft: 0,
    list: [] as any[],
    brandList: [] as any[],
    currentTabList: [] as number[],
    brandTabList: [] as number[],
    scrollTop: false,
    lists: [] as any[],
    brandLists: [] as any[],
    advertisingList: [] as any[],
    index: 0,
    navBottom: [
      { icon: '/images/ico_cai@2x.png', name: '品牌直采' },
      { icon: '/images/ico_zheng@2x.png', name: '假一赔十' },
      { icon: '/images/ico_zhi@2x.png', name: '超值低价' },
      { icon: '/images/ico_tui@2x.png', name: '售后无忧' },
    ],
    /** 品牌 */
    makes: [] as any[],
    /** 选中的品牌下标 */
    makeIndex: 0,
    carts: 0,
    //  tabbar 小红点检查，第一次加载页面时需要获取
    hadGetNewMsg: false,
  },

  async onLoad() {
    const navData = await mallApi.getCategories()
    navData.map((item) => (item.page = 1))
    this.setData({
      navData: [...this.data.navData, ...navData],
    })
    $event.on('after:payCarts', this, () => {
      this.getCarts()
    })
    $event.on('change:payCarts', this, () => {
      this.getCarts()
    })
    if (isLogin()) {
      this.getCarts()
    }
    $event.on('message:showMessageDot', this, (isShow) => {
      if (typeof this.getTabBar === 'function' && this.getTabBar()) {
        this.setData({
          hadGetNewMsg: true,
        })
        this.getTabBar().setData({
          showMeesageDot: isShow,
        })
      }
    })
    $event.on('message:showMineDot', this, (isShow) => {
      if (typeof this.getTabBar === 'function' && this.getTabBar()) {
        this.getTabBar().setData({
          showMineDot: isShow,
        })
      }
    })
  },
  async onShow() {
    // 自定义tab
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 1,
      })
    }
    $event.on('after:boot', this, () => {
      this.getPosition()
    })
    this.getPosition()
    const {
      data: { index, makeIndex, currentTab },
    } = this
    this.setData(
      +index === 0
        ? {
            [`navData[${currentTab}].isLastPage`]: this.data.navData[currentTab].isLastPage
              ? this.data.navData[currentTab].isLastPage
              : false,
            [`navData[${currentTab}].page`]: this.data.navData[currentTab].page
              ? this.data.navData[currentTab].page
              : 1,
            [`list[${currentTab}]`]: [],
          }
        : {
            [`makes[${makeIndex}].isLastPage`]: this.data.makes[makeIndex].isLastPage
              ? this.data.makes[makeIndex].isLastPage
              : false,
            [`makes[${makeIndex}].page`]: this.data.makes[makeIndex].page
              ? this.data.makes[makeIndex].page
              : 1,
            [`brandList[${makeIndex}]`]: [],
          },
    )
    if (this.data.lists.length == 0) {
      await this.onReset()
    }
    if (isLogin()) {
      if (!this.data.hadGetNewMsg) {
        getNotifications()
      }
    }
  },
  onShareAppMessage() {
    return {
      path: $utils.getSharePath(),
    }
  },
  onPageScroll() {
    this.fixedNav()
  },
  /** 购物车商品数量 */
  async getCarts() {
    const carts = await mallApi.getCartsCount()
    this.setData({
      carts: carts.count,
    })
  },
  async onPullDownRefresh() {
    const {
      data: { index, makeIndex, currentTab },
    } = this
    this.setData(
      +index === 0
        ? {
            [`navData[${currentTab}].isLastPage`]: false,
            [`navData[${currentTab}].page`]: 1,
            [`list[${currentTab}]`]: [],
          }
        : {
            [`makes[${makeIndex}].isLastPage`]: false,
            [`makes[${makeIndex}].page`]: 1,
            [`brandList[${makeIndex}]`]: [],
          },
    )
    await this.onReset()
    wx.stopPullDownRefresh()
  },
  async onReset(more = false) {
    const {
      data: {
        currentTab,
        index,
        makeIndex,
        makes,
        navData,
        currentTabList,
        brandTabList,
        brandList,
      },
    } = this
    if (
      (+index === 0 && navData[currentTab].isLastPage) ||
      (+index === 1 && makes[makeIndex].isLastPage)
    ) {
      return
    }
    wx.showLoading({
      title: '加载中',
    })
    let data = {} as GetCommoditiesParmas
    data =
      +index === 0
        ? {
            category_id: currentTab > 0 ? navData[currentTab].id : '',
            page: navData[currentTab].page ? navData[currentTab].page : 1,
            order: 'topped_at desc, updated_at desc',
            limit: 20,
            type: 'ticket',
            with: '',
            liked: 'check',
          }
        : {
            brand_id: makes[makeIndex].id,
            page: makes[makeIndex].page ? makes[makeIndex].page : 1,
            order: 'topped_at desc, updated_at desc',
            limit: 20,
            type: 'ticket',
            liked: 'check',
          }
    const list = await mallApi.getCommodities(data)
    const isLastPage =
      list.meta.last_page === list.meta.current_page || list.meta.last_page < list.meta.current_page
    if (+index === 0) {
      /**分类 */
      currentTabList.push(currentTab)
      this.setData({
        [`list[${currentTab}]`]: this.data.list[currentTab]
          ? [...this.data.list[currentTab], ...list.data]
          : list.data,
        [`navData[${currentTab}].isLastPage`]: isLastPage,
        currentTabList,
        [`navData[${currentTab}].page`]: list.meta.current_page + 1,
        [`navData[${currentTab}].show`]: list.data.length === 0 ? true : false,
        lists: this.data.lists && more ? [...this.data.lists, ...list.data] : list.data,
      })
    } else {
      /** 品牌 */
      brandTabList.push(makeIndex)
      this.setData({
        [`brandList[${makeIndex}]`]: brandList[makeIndex]
          ? [...brandList[makeIndex], ...list.data]
          : list.data,
        [`makes[${makeIndex}].isLastPage`]: isLastPage,
        brandTabList,
        [`makes[${makeIndex}].page`]: list.meta.current_page,
        [`makes[${makeIndex}].show`]: list.data.length === 0 ? true : false,
        brandLists:
          this.data.brandLists && more ? [...this.data.brandLists, ...list.data] : list.data,
      })
    }
    wx.hideLoading()
  },
  async onReachBottom() {
    await this.onReset(true)
  },
  getPosition() {
    this.setData!({
      navigationHeight: GlobalData.navigationHeight,
      access: GlobalData.access,
      currencyName: GlobalData.currencyName,
      [`navData[${0}].icon.url`]: GlobalData.mall.all_categories_icon
        ? GlobalData.mall.all_categories_icon.url
        : '/images/ico_type_01@2x.png',
    })
  },
  onDownload() {
    $event.emit('download')
  },
  switchNav(event: WechatMiniprogram.CustomEvent) {
    const windowWidth = GlobalData.clientWidth
    const cur = event.currentTarget.dataset.current
    //每个tab选项宽度占1/5
    const singleNavWidth = windowWidth / 5
    //tab选项居中
    this.setData({
      navScrollLeft: (cur - 2) * singleNavWidth,
    })
    if (this.data.currentTab == cur) {
      return
    } else {
      this.setData({
        currentTab: cur,
      })
      this.switchList()
    }
  },
  switchList() {
    //tab选中的改变和siwper滑动改变的方法写在这里
    const cur = this.data.currentTab
    //没有有缓存，切换Tab请求数据
    if (this.data.currentTabList.indexOf(cur) === -1) {
      this.onReset()
    } else {
      this.setData({
        lists: this.data.list[cur],
      })
    }
  },
  toSerch() {
    const categoryId = this.data.currentTab
    wx.navigateTo({ url: `/mall/search/search?categoryId=${categoryId}` })
  },
  // toDetail(event: WechatMiniprogram.BaseEvent) {
  //   const data = event.currentTarget.dataset as { commodityId: number }
  //   wx.navigateTo({ url: `/mall/detail/detail?commodityId=${data.commodityId}` })
  // },
  /** 判断是否滚动到了商品列表 */
  fixedNav() {
    const query = wx.createSelectorQuery().in(this)
    query.select('#nav').boundingClientRect()
    query.selectViewport().scrollOffset()
    query.exec((res: any) => {
      this.setData({
        scrollTop: res[0] ? res[0].bottom < 1 : true,
      })
    })
  },
  /** 选择类型(品牌,分类) */
  async chooseType(e: WechatMiniprogram.BaseEvent) {
    const {
      currentTarget: {
        dataset: { index },
      },
    } = e
    let {
      data: { makes },
    } = this
    if (index === this.data.index) return
    this.setData({ index })
    if (makes.length === 0) {
      makes = await mallApi.getBrands({ offset: 0, limit: 17 })
      this.setData({ makes })
      this.onReset()
    }
  },
  /** 点击品牌 */
  chooseMake(e: WechatMiniprogram.BaseEvent) {
    const {
      currentTarget: {
        dataset: { makeIndex },
      },
    } = e
    const {
      data: { brandTabList, brandList, makeIndex: index, makes },
    } = this
    if (makeIndex === index) return
    this.setData({ makeIndex, brandId: makes[makeIndex].id })
    //没有有缓存，切换Tab请求数据
    if (brandTabList.indexOf(makeIndex) === -1) {
      this.onReset()
    } else {
      this.setData({
        brandLists: brandList[makeIndex],
      })
    }
  },
  /** 点击更多，跳转选择品牌 */
  chooseBrands() {
    wx.navigateTo({
      url: '/mall/publish/chooseBrands/chooseBrands?id=1',
    })
  },
  /** 到购物车 */
  toCarts() {
    wx.navigateTo({
      url: '/mall/buyCar/buyCar',
    })
  },
})
